package ucd.csi.comp30220.fall2011.oteop.flughafen.impl;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import ucd.csi.comp30220.fall2011.oteop.OTEOP;
import ucd.csi.comp30220.fall2011.oteop.flight.FlightInfo;
import ucd.csi.comp30220.fall2011.oteop.flughafen.Airport;
import ucd.csi.comp30220.fall2011.oteop.flughafen.AirportException;
import ucd.csi.comp30220.fall2011.oteop.flughafen.AirportInfo;
import ucd.csi.comp30220.fall2011.oteop.util.EndPoint;
import ucd.csi.comp30220.fall2011.oteop.util.ServiceFinder;

public class RemoteAirportClient implements Airport {
    
    private Registry registry;
    private RemoteAirport client;
    
    public RemoteAirportClient(final String code, long timeout) throws Exception {
        EndPoint endPoint = ServiceFinder.findService(
            OTEOP.JMDNS_TYPE_TCP_LOCAL, Airport.JMDNS_SUB_TYPE, code, timeout);
        if (endPoint == null)
            throw new Exception("Failed to get Airport in " +timeout +"ms");
        String host = endPoint.getHost();
        int port = endPoint.getPort();
        registry = LocateRegistry.getRegistry(host, port);
        client = (RemoteAirport)(registry.lookup(code));
    }
    
    public AirportInfo getInfo() throws AirportException {
        try {
            return client.getInfo();
        } catch (RemoteException re) { 
            throw new AirportException("Unable to contact remote Airport", re);
        }
    }

    public void dispatchFlight(FlightInfo flightInfo) throws AirportException {
        try {
            client.dispatchFlight(flightInfo);
        } catch (RemoteException re) { 
            throw new AirportException("Unable to contact remote Airport", re);
        }
    }
    
    public void acceptFlight(FlightInfo flightInfo) throws AirportException {
        try {
            client.acceptFlight(flightInfo);
        } catch (RemoteException re) { 
            throw new AirportException("Unable to contact remote Airport", re);
        }
    }
}
